//
//  RHSocCircleView.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/13.
//

#import "RHSocCircleView.h"
@interface RHSocCircleView()
//大绿色渐变圆环线宽
@property (nonatomic, assign) CGFloat bigGreenGradientLineWidth;
//大绿色渐变圆环半径
@property (nonatomic, assign) CGFloat bigGreenRadius;
//中心点
@property (nonatomic, assign) CGPoint circleCenter;
//小绿色圆环线宽
@property (nonatomic, assign) CGFloat smallGreenLineWidth;
//圆环间的间距
@property (nonatomic, assign) CGFloat lineMargin;
//四周边距
@property (nonatomic, assign) UIEdgeInsets padding;

//大绿色渐变圆环
@property (nonatomic, strong) CAGradientLayer *bigGreenGradientLayer;

@property (nonatomic, strong) CAShapeLayer *bigGreenShaper;

//小绿色渐变圆环
@property (nonatomic, strong) CAGradientLayer *smallGreenGradientLayer;

@property (nonatomic, strong) CAShapeLayer *smallGreenShaper;

//刻度
@property (nonatomic, strong) CAShapeLayer *markShaper;

//开始角度
@property (nonatomic, assign) CGFloat startAngle;
//开始角度
@property (nonatomic, assign) CGFloat endAngle;
//当前角度
@property (nonatomic, assign) CGFloat currentAngle;
//总弧度
@property (nonatomic, assign) CGFloat totalAngle;

@property (nonatomic, strong) UIImageView *indicatorImg;

@property (nonatomic, strong) UIImageView *pointImg;
//功率
@property (nonatomic, strong) QMUILabel *powerLab;
//装机容量
@property (nonatomic, strong) QMUILabel *capacityLab;

@property (nonatomic, strong) QMUILabel *leftLab;

@property (nonatomic, strong) QMUILabel *rightLab;

@property (nonatomic, assign) CGFloat lastPointValue;
@end
@implementation RHSocCircleView

-(instancetype)initWithFrame:(CGRect)frame
{
    if([super initWithFrame:frame]){
        [self config];
        [self createSubLayer];
    }
    return self;
}

-(void)config{
    self.backgroundColor = [UIColor whiteColor];
    _bigGreenGradientLineWidth = 8;
    _bigGreenRadius = MIN(self.width,self.height)/2  - _bigGreenGradientLineWidth/2 +10;
    _smallGreenLineWidth = 2;
    _lineMargin = 15;
    _padding = UIEdgeInsetsMake(5, 5, 5, 5);
    //大绿色圆环的起始角度
    _startAngle   = M_PI - 5*M_PI/180;
    _endAngle     = 0 + 5*M_PI/180;
    _totalAngle   = M_PI + 10*M_PI/180;
    _currentAngle = _startAngle;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [self addGestureRecognizer:pan];
}




- (void)layoutSubviews
{
    [super layoutSubviews];
    _bigGreenGradientLayer.frame   = self.bounds;
    _bigGreenShaper.frame          = self.bounds;
    _smallGreenGradientLayer.frame = self.bounds;
    _smallGreenShaper.frame        = self.bounds;
    _markShaper.frame              = self.bounds;
    _bigGreenRadius = MIN(self.width,self.height)/2  - _bigGreenGradientLineWidth/2 +10;
    _circleCenter = CGPointMake(self.width/2, self.height/2 + 40);
    
    [self.leftLab mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_offset(-_bigGreenRadius);
    }];
    
    [self.rightLab mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_offset(_bigGreenRadius);
    }];
    [self setNeedsDisplay];
}

-(void)setProgress:(CGFloat)progress
{
    _progress = progress;
    _currentAngle = _startAngle + progress*(M_PI + 10*M_PI/180);
    self.powerLab.text = [NSString stringWithFormat:@"%ld%%",(NSInteger)(self.progress*100)];
    [self setNeedsDisplay];
}

-(void)setPower:(CGFloat)power
{
    _power = power;
    self.isChg = power >= 0;
}

-(void)setIsChg:(BOOL)isChg
{
    _isChg = isChg;
    self.pointImg.image = [UIImage imageNamed:self.isChg? @"soc_point_green":@"soc_point_blue"];
    self.indicatorImg.image = [UIImage imageNamed:self.isChg? @"soc_indicator_green":@"soc_indicator_blue"];
    _bigGreenGradientLayer.colors = self.isChg? @[(id)kCOLOR_HEX(@"97F3DE").CGColor,(id)kCOLOR_HEX(@"31D3AE").CGColor]:@[(id)kCOLOR_HEX(@"B3C7F9").CGColor,(id)kCOLOR_HEX(@"678EF2").CGColor];
    _smallGreenGradientLayer.colors = self.isChg? @[(id)kCOLOR_HEX_A(@"98F3B1", 0.2).CGColor,(id)kCOLOR_HEX_A(@"2EDAB3", 0.2).CGColor]:@[(id)kCOLOR_HEX_A(@"B6BDFF", 0.2).CGColor,(id)kCOLOR_HEX_A(@"5A9CF1", 0.2).CGColor];
    [self setNeedsDisplay];
}

-(void)createSubLayer
{
    //================大渐变圆环===============
    _bigGreenGradientLayer = [[CAGradientLayer alloc]init];
    _bigGreenGradientLayer.colors = self.power>=0?@[(id)kCOLOR_HEX(@"97F3DE").CGColor,(id)kCOLOR_HEX(@"31D3AE").CGColor]:@[(id)kCOLOR_HEX(@"B3C7F9").CGColor,(id)kCOLOR_HEX(@"678EF2").CGColor];
    _bigGreenGradientLayer.startPoint = CGPointMake(0, 0.5);
    _bigGreenGradientLayer.endPoint = CGPointMake(1, 0.5);
    _bigGreenGradientLayer.frame = self.bounds;
    [self.layer addSublayer:_bigGreenGradientLayer];
    
    _bigGreenShaper = [CAShapeLayer layer];
    _bigGreenShaper.frame = self.bounds;
    [self.layer addSublayer:_bigGreenShaper];
    _bigGreenShaper.fillColor = [[UIColor clearColor]CGColor];
    _bigGreenShaper.strokeColor = [[UIColor redColor]CGColor];
    _bigGreenShaper.lineWidth = _bigGreenGradientLineWidth;
    _bigGreenShaper.lineCap = kCALineCapRound;
    
    //刻度
    _markShaper = [CAShapeLayer layer];
    _markShaper.frame = self.bounds;
    [self.layer addSublayer:_markShaper];
    _markShaper.fillColor = [[UIColor clearColor]CGColor];
    _markShaper.strokeColor = [[UIColor redColor]CGColor];
    _markShaper.lineWidth = 4;
    _markShaper.lineCap = kCALineCapButt;
    _markShaper.strokeColor = kCOLOR_HEX(@"FFFFFF").CGColor;
    
    //小渐变圆环
    _smallGreenGradientLayer = [[CAGradientLayer alloc]init];
    _smallGreenGradientLayer.colors = @[(id)kCOLOR_HEX_A(@"98F3B1", 0.2).CGColor,(id)kCOLOR_HEX_A(@"2EDAB3", 0.2).CGColor];
    _smallGreenGradientLayer.startPoint = CGPointMake(0, 0.5);
    _smallGreenGradientLayer.endPoint = CGPointMake(1, 0.5);
    _smallGreenGradientLayer.frame = self.bounds;
    [self.layer addSublayer:_smallGreenGradientLayer];
    
    _smallGreenShaper = [CAShapeLayer layer];
    _smallGreenShaper.frame = self.bounds;
    [self.layer addSublayer:_smallGreenShaper];
    _smallGreenShaper.fillColor = [[UIColor clearColor]CGColor];
    _smallGreenShaper.strokeColor = [[UIColor redColor]CGColor];
    _smallGreenShaper.lineWidth = _smallGreenLineWidth;
    _smallGreenShaper.lineCap = kCALineCapRound;
    
    
    UIImage *img = [UIImage imageNamed:@"soc_point_green"];
    _pointImg = [[UIImageView alloc]initWithImage:img];
    _pointImg.contentMode = UIViewContentModeScaleAspectFill;
    _pointImg.size = CGSizeMake(18, 18);
    [self addSubview:_pointImg];
    
    UIImage *img2 = [UIImage imageNamed:@"soc_indicator_green"];
    _indicatorImg = [[UIImageView alloc]initWithImage:img2];
    _indicatorImg.contentMode = UIViewContentModeScaleAspectFill;
    _indicatorImg.size = CGSizeMake(5, 5);
    [self addSubview:_indicatorImg];
    
    QMUILabel *powerTitleLab = [[QMUILabel alloc]init];
    powerTitleLab.text = @"0%";
    powerTitleLab.font = [UIFont systemFontOfSize:16];
    powerTitleLab.textColor = kCOLOR_HEX_A(@"3F4443", 0.8);
    [self addSubview:powerTitleLab];
    self.powerLab = powerTitleLab;
    [powerTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_offset(25);
        make.centerX.mas_offset(0);
    }];
    
    QMUIButton *reduceBtn = [[QMUIButton alloc]init];
    [reduceBtn setTitle:@"-" forState:UIControlStateNormal];
    [reduceBtn setTitleColor:kCOLOR_HEX_A(@"3F4443", 0.3) forState:UIControlStateNormal];
    reduceBtn.titleLabel.font = kSYSTEMFONT(12);
    [self addSubview:reduceBtn];
    [reduceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(30);
        make.centerY.equalTo(powerTitleLab);
        make.right.equalTo(powerTitleLab.mas_left).offset(3);
    }];
   
    QMUIButton *addBtn = [[QMUIButton alloc]init];
    [addBtn setTitle:@"+" forState:UIControlStateNormal];
    [addBtn setTitleColor:kCOLOR_HEX_A(@"3F4443", 0.3) forState:UIControlStateNormal];
    addBtn.titleLabel.font = kSYSTEMFONT(12);
    [self addSubview:addBtn];
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(30);
        make.centerY.equalTo(powerTitleLab);
        make.left.equalTo(powerTitleLab.mas_right).offset(-3);
    }];
    
    kWeakSelf;
    [[addBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        if(weakSelf.progress < 1.0){
            weakSelf.progress += 0.01;
            if(weakSelf.progress>1){
                weakSelf.progress = 1;
            }
        }
    }];
    
    [[reduceBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        if(weakSelf.progress > 0.0){
            weakSelf.progress -= 0.01;
            if(weakSelf.progress < 0){
                weakSelf.progress = 0;
            }
        }
    }];
}


-(void)drawRect:(CGRect)rect
{
    
    
    //灰色
    UIBezierPath *bigGraytPath = [UIBezierPath bezierPathWithArcCenter:_circleCenter radius:_bigGreenRadius startAngle:_startAngle endAngle:_endAngle clockwise:YES];
    bigGraytPath.lineWidth = _bigGreenGradientLineWidth;
    [kCOLOR_HEX(@"EBEBEB") set];
    bigGraytPath.lineCapStyle = kCGLineCapRound;
    [bigGraytPath stroke];
    
    //大渐变圆环
    CGFloat bigGradientEndAngle = _startAngle + self.progress * self.totalAngle;
    if(self.progress == 0){
        bigGradientEndAngle = _startAngle + 0.001 * M_PI/180.0;
    }
    UIBezierPath *bigGreenGradientPath = [UIBezierPath bezierPathWithArcCenter:_circleCenter radius:_bigGreenRadius startAngle:_startAngle endAngle:bigGradientEndAngle clockwise:YES];
    
    _bigGreenShaper.path = bigGreenGradientPath.CGPath;
    _bigGreenGradientLayer.mask = _bigGreenShaper;
    
    
    //小渐变圆环
    CGFloat greenRadius = _bigGreenRadius - _bigGreenGradientLineWidth/2 - _lineMargin - _smallGreenLineWidth/2;
    UIBezierPath *greenPath = [UIBezierPath bezierPathWithArcCenter:_circleCenter radius:greenRadius startAngle:_startAngle endAngle:_endAngle clockwise:YES];
    _smallGreenShaper.path = greenPath.CGPath;
    _smallGreenGradientLayer.mask = _smallGreenShaper;
    
    self.pointImg.center = [self calculateTextPositonWithArcCenter:_circleCenter Angle:_currentAngle radius:_bigGreenRadius];
    
    self.indicatorImg.center = [self calculateTextPositonWithArcCenter:_circleCenter Angle:_currentAngle radius:_bigGreenRadius - 15];
    self.indicatorImg.transform = CGAffineTransformMakeRotation(_currentAngle);
    
    CGFloat width = [@"0" getStringWidthFont:[UIFont systemFontOfSize:8] limitHeight:15];
    
    [@"0" drawAtPoint:CGPointMake(_circleCenter.x - _bigGreenRadius -10 - width, _circleCenter.y) withAttributes:@{NSForegroundColorAttributeName:self.isChg?kCOLOR_HEX(@"4FDDBC"):kCOLOR_HEX(@"678EF2")}];
    
    width = [@"50" getStringWidthFont:[UIFont systemFontOfSize:8] limitHeight:15];
    [@"50" drawAtPoint:CGPointMake(_circleCenter.x - width/2, _circleCenter.y - _bigGreenRadius - 5 - 15) withAttributes:@{NSForegroundColorAttributeName:self.isChg?kCOLOR_HEX(@"4FDDBC"):kCOLOR_HEX(@"678EF2")}];
    
    width = [@"100" getStringWidthFont:[UIFont systemFontOfSize:8] limitHeight:15];
    [@"100" drawAtPoint:CGPointMake(_circleCenter.x + _bigGreenRadius +10 , _circleCenter.y) withAttributes:@{NSForegroundColorAttributeName:self.isChg?kCOLOR_HEX(@"4FDDBC"):kCOLOR_HEX(@"678EF2")}];
    
    //刻度
    NSInteger scaleNumber = 5;
    CGFloat perAngle = self.totalAngle/scaleNumber;
    UIBezierPath *markPath = [UIBezierPath bezierPath];
    for (int i = 0; i<scaleNumber; i++) {
        if(i == 0) continue;
        CGFloat width = 6;
          
        CGFloat startAngel = _startAngle+perAngle*i;
        CGFloat endAngel = startAngel + M_PI/180;//刻度线的宽度
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:_circleCenter radius:_bigGreenRadius startAngle:startAngel endAngle:endAngel clockwise:YES];
    
        [markPath appendPath:path];
    }
    
    self.markShaper.path = markPath.CGPath;
}




//根据弧度计算位置
- (CGPoint)calculateTextPositonWithArcCenter:(CGPoint)center
                                       Angle:(CGFloat)angel radius:(CGFloat)redius
{
    CGFloat x = redius * cosf(angel);
    CGFloat y = redius * sinf(angel);
    
    return CGPointMake(center.x + x, center.y + y);
}


-(void)panAction:(UIPanGestureRecognizer*)gesture
{
    CGPoint touchPoint = [gesture locationInView:self];
    NSLog(@"---->移动的位置:%@",NSStringFromCGPoint(touchPoint));
    //最小位置
    CGFloat minX = 0;
    CGFloat maxX = self.width ;
    CGFloat minY = 0;
    CGFloat y = (_bigGreenRadius) * sinf(_startAngle);
    CGFloat maxY = self.height;
    if (touchPoint.x < minX || touchPoint.x>maxX) {
        return;
    }
    if (touchPoint.y<minY || touchPoint.y > maxY) {
        return;
    }
    //将点的位置转成弧度
    CGFloat angle = atan2f(touchPoint.y-self.circleCenter.y, touchPoint.x - self.circleCenter.x);
    //过滤   不能大于1.047197551196598弧度  一角度等于0.017453292519943弧度
    //头尾预留10度的滑动空间  M_PI/180*20
//     NSLog(@"======================过滤前的弧度:%f",angle);
    if (angle> _endAngle + (10 *M_PI/180) && angle < _startAngle ) {
//        NSLog(@">>>>超出最大最小弧度:%f",angle);
        return;
    }

    //上半周角度的处理,上半周的弧度范围 为 -3.14 到 0 ,下半周的弧度范围为 0 到 3.14
    //这里转成正数 0 到6.28
    CGFloat endAngle = 0.0;
    if (angle<0) {
        endAngle += M_PI + (M_PI+angle);
    }else{
        endAngle = angle;
    }
//    //头尾的处理
//    if (endAngle>M_PI/3 && endAngle<(M_PI/3+M_PI/180*20)) {
//        endAngle = M_PI/3;
//    }
//    if (endAngle<M_PI*2/3 && endAngle>(M_PI*2/3-M_PI/180*20)) {
//        endAngle = M_PI*2/3;
//    }
//    NSLog(@"----------当前过滤后弧度:%f",endAngle);
    //算出位置
    CGFloat px = _bigGreenRadius * cosf(endAngle);
    CGFloat py = _bigGreenRadius * sinf(endAngle);
    
    _currentAngle = endAngle;
//    NSLog(@"------>当前弧度:%f",_currentAngle);
    CGFloat progress = 0;
    if(_currentAngle <= self.endAngle + 10 *M_PI/180){
        progress = (_currentAngle + 2*M_PI - _startAngle) / self.totalAngle;
    }else{
        progress = (_currentAngle  - _startAngle) / self.totalAngle;
    }
//    NSLog(@"---->%f",self.progress);
    if(progress <0){
        progress = 0;
    }
    if(progress >1){
        progress = 1;
    }
    self.progress = progress;
    self.policyModel.soc = [NSString stringWithFormat:@"%ld",(NSInteger)(progress*100)];
}



@end
